const {
	createClient,
	segment
} = require("oicq");


const net = require('net');
const port = 44556;
const hostname = '127.0.0.1';
const verification = "xiaohuaijava"
let bot = null

let currentClient = null

// 创建服务器
const server = new net.createServer();

server.on('connection', (client) => {
	console.log(`获取到客户端连接,address=${client.remoteAddress},port=${client.remotePort}`)

	client.on('error', function(e) {
		console.log('client error' + e);
		client.end();
	});

	client.on('close', function() {
		console.log(`客户端下线了`);
	});

	client.on('data', function(data) {
		try {
			/**
			 * 这样能解决一些问题
			 */
			let res = data.toString().split("\0")
			res.pop()
			res.forEach(data => {
				let result = null
				try {
					result = JSON.parse(data)
				} catch (e) {
					console.error("解析json出错", data)
				}
				if (result != null) {
					if (Array.isArray(result)) {
						result.forEach(handlerResult)
					} else {
						handlerResult(result)
					}
				}
			})

			function handlerResult(result) {
				if ('login' === result.type) {
					if (result.data.verification !== verification) {
						console.log("身份验证错误", result)
						client.write(JSON.stringify({
							isSystemInfo: true,
							msg: "身份验证失败"
						}))
						return
					}
					currentClient = client
					//登录行为
					if (bot === null) {
						//机器人不存在，则创建机器人
						bot = createClient(result.data.qq)
						//机器人上线
						bot.on("system.online", () => console.log("Bot logged in!"))

						//机器人收到消息
						bot.on("message", e => {
							let obj = {}
							if (e.message_type === 'group') {
								let keys = ["message_type", "message_id", "time", "self_id",
									"group_id", "group_name", "atme", "raw_message",
									"message", "user_id"
								]
								for (let k of keys) {
									obj[k] = e[k]
								}
								console.log("转发群消息", obj)
								currentClient.write(JSON.stringify(obj))
							} else if (e.message_type === 'private') {
								let keys = ["message_type", "message_id", "time", "self_id",
									"from_id", "raw_message", "message"
								]
								for (let k of keys) {
									obj[k] = e[k]
								}
								obj.user_nickname = e.sender.nickname
								console.log("转发私有消息", obj)
								currentClient.write(JSON.stringify(obj))
							} else {
								console.log("未转发的消息", e)
							}

						})

						bot.on("system.login.qrcode", function(e) {
							//扫码后按回车登录
							process.stdin.once("data", () => {
								this.login()
							})
						})

						//监听并输入滑动验证码ticket
						bot.on("system.login.slider", (data) => {
							process.stdin.once("data", (input) => {
								bot.sliderLogin(input);
							});
						});

						bot.login(result.data.pwd);
					} else {
						console.log("机器人已存在,将不进行登录")
						//机器人已存在，给出提示信息
						currentClient.write(JSON.stringify({
							isSystemInfo: true,
							msg: "机器人已经登录"
						}))
					}
				} else if ("replyGroup" === result.type) {
					//群里回复
					console.log("replyGroup", result)
					if (bot != null) {
						bot.pickGroup(result.data.grp).sendMsg(parseMessage(result.data.reply))
					} else {
						console.log("bot is null by replyGroup")
					}

				} else if ("replyPrivate" === result.type) {
					//私聊回复某人
					if (bot != null) {
						console.log("replyPrivate暂未实现", result)
					} else {
						console.log("bot is null by replyPrivate")
					}
				} else if ("groupBan" === result.type) {
					//群里禁言某人
					if (bot != null) {
						console.log("groupBan暂未实现", result)
					} else {
						console.log("bot is null by groupBan")
					}
				} else {
					//无法处理的消息
					console.log("无法处理的消息", result)
				}
			}
		} catch (e) {
			console.error("错误", e)
		}
	});
});

server.listen(port, function() {
	console.log(`node server run as ：http://${hostname}:${port} wait java client connecting...`);
});

function initBot(result, handleMessage) {
	bot = createClient(result.data.qq);

	bot.on("system.login.slider", (data) => {
		process.stdin.once("data", (input) => {
			bot.sliderLogin(input);
		});
	});
	//收到的数据转发给java
	bot.on("message", handleMessage);

	bot.login(result.data.pwd);
}

function parseMessage(data) {
	//data是数组
	let res = []
	console.log("parseMessage", data)
	data.forEach(item => {
		if (item.type === 'text') {
			res.push(segment.text(item.text))
		} else if (item.type === 'at') {
			res.push(segment.at(item.qq, item.text))
		} else if (item.type === 'image') {
			res.push(segment.image(item.url))
		} else {
			console.log("无法解析的Message", item)
		}
	})
	return res
}
